/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import bd.Consultas;
import java.sql.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
//import net.sf.jasperreports.engine.JRException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import bd.HibernateUtil;
import java.awt.Cursor;
//import lixo.SplashScreen;

/**
 *
 * @author Edu
 */
public class TelaLogin extends javax.swing.JDialog {

    
    
     
     public static String USUARIO_LOGADO;
     
    public TelaLogin(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    TelaLogin()
    {
        initComponents();
        
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonOK = new javax.swing.JButton();
        jPasswordFieldSenha = new javax.swing.JPasswordField();
        jTextFieldUsuario = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SoftlabS - V 1.0 - LOGIN");
        setBackground(java.awt.Color.red);
        setMinimumSize(new java.awt.Dimension(500, 500));
        setResizable(false);
        getContentPane().setLayout(null);

        jButtonOK.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButtonOK.setText("OK");
        jButtonOK.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });
        getContentPane().add(jButtonOK);
        jButtonOK.setBounds(350, 420, 120, 40);

        jPasswordFieldSenha.setForeground(new java.awt.Color(102, 102, 102));
        jPasswordFieldSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordFieldSenhaActionPerformed(evt);
            }
        });
        getContentPane().add(jPasswordFieldSenha);
        jPasswordFieldSenha.setBounds(180, 250, 230, 30);

        jTextFieldUsuario.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jTextFieldUsuario.setForeground(new java.awt.Color(102, 102, 102));
        jTextFieldUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldUsuarioActionPerformed(evt);
            }
        });
        getContentPane().add(jTextFieldUsuario);
        jTextFieldUsuario.setBounds(180, 200, 230, 30);

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButton1.setText("Sair");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(250, 420, 80, 40);

        jLabel6.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jLabel6.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/figura/login mini.jpg"))); // NOI18N
        jLabel6.setEnabled(false);
        jLabel6.setOpaque(true);
        getContentPane().add(jLabel6);
        jLabel6.setBounds(0, 0, 495, 480);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
      dispose();
    }//GEN-LAST:event_jButton1ActionPerformed


    //private void jPasswordFieldSenhaActionPerformed(java.awt.event.ActionEvent evt) {                                                    
    //    String driver = "org.postgresql.Driver";  
    //    String user   = "postgres";  
   //    String senha = "ewq321";  
     //   String url      = "jdbc:postgresql://localhost:5432/postgres";  

      public void alteraCursor(int tipo) {

        
        if (tipo == 1) {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        }
         if (tipo == 0) {
        setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
        
    }
      
    private void jPasswordFieldSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordFieldSenhaActionPerformed
       
        jButtonOKActionPerformed(evt);
    }//GEN-LAST:event_jPasswordFieldSenhaActionPerformed

    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
        String driver = "org.postgresql.Driver";
        String user = "postgres";
        String senha = "postgres";

       // String url = "jdbc:postgresql://localhost:5432/postgres";


        String url = "jdbc:postgresql://186.202.177.241:5432/postgres";


        if (jTextFieldUsuario.getText().equals("") || jPasswordFieldSenha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Login ou Senha inválido.", "", JOptionPane.ERROR_MESSAGE);
        } else {
            alteraCursor(1);
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(TelaLogin.class.getName()).log(Level.SEVERE, null, ex);
            }

            Connection con = null;

            try {
                con = (Connection) DriverManager.getConnection(url, user, senha);
                Statement stm = con.createStatement();
                //String sql = "select * from usuario where usuario = '" + jTextFieldUsuario.getText() + "' and  senha = '" + jPasswordFieldSenha.getText() + "'";
                String sql = "select * from funcionario where usuario = '" + jTextFieldUsuario.getText() + "' and  senha = '" + jPasswordFieldSenha.getText() + "'";
                ResultSet rs = stm.executeQuery(sql);
                System.out.println("Conexão realizada com sucesso.");
                boolean UsuarioCorreto = false;

                while (rs.next()) {
                    String loginn = rs.getString("usuario");
                    String senhaa = rs.getString("senha");

                    if (jTextFieldUsuario.getText().equals(loginn) && jPasswordFieldSenha.getText().equals(senhaa)) {
                        //JOptionPane.showMessageDialog(null, "Seja bem vindo: " + loginn, "", JOptionPane.INFORMATION_MESSAGE);
                  //      SplashScreen splash = new SplashScreen();
                    //    splash.showSplashAndExit();
                        TelaPrincipal tp = new TelaPrincipal(loginn);
                        tp.setExtendedState(TelaPrincipal.NORMAL);
                        tp.setVisible(true);
                        dispose();
                        UsuarioCorreto = true;
                    //    splash.disposeSplash();
                        Consultas.abrirSessao();
                        USUARIO_LOGADO = loginn;

                    }
                }
                if (!UsuarioCorreto) {
                    JOptionPane.showMessageDialog(null, "Login ou Senha inválido.", "", JOptionPane.ERROR_MESSAGE);
                    jTextFieldUsuario.setText("");
                    jPasswordFieldSenha.setText("");
                    jTextFieldUsuario.requestDefaultFocus();
                    alteraCursor(0);
                }
                
            } catch (SQLException ex) {
                
                Logger.getLogger(TelaLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                con.close();
                System.out.println("fechamento da conexão");
               
            } catch (SQLException onConClose) {
                System.out.println("Houve erro no fechamento da conexão");
                JOptionPane.showMessageDialog(null, "Erro na conexão, com o banco de dados!", "", JOptionPane.WARNING_MESSAGE);
                onConClose.printStackTrace();
               
            }
        }
    }//GEN-LAST:event_jButtonOKActionPerformed

    private void jTextFieldUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldUsuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldUsuarioActionPerformed

    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TelaLogin dialog = new TelaLogin(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonOK;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPasswordField jPasswordFieldSenha;
    private javax.swing.JTextField jTextFieldUsuario;
    // End of variables declaration//GEN-END:variables
}
